package com.enthal.basicpers

import android.app.NotificationManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.IBinder
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import android.util.Log
import android.widget.Toast


// https://blog.csdn.net/qq_41123894/article/details/100182627
// https://blog.csdn.net/Vanswells/article/details/81033280
// https://www.cnblogs.com/yaowen/p/5673960.html

class NoticeListenerService : NotificationListenerService() {

    /**
     * 只会在未建立时执行一次
     * onCreate用于初始化工作，多次调用startService启动同一个服务，onCreate方法只会被调用一次，
     * onStartCommand会被调用多次，onDestory在销毁时也只会被调用一次。
     */
    override fun onCreate() {
        super.onCreate()
        Toast.makeText(applicationContext, "Notice Listener Created", Toast.LENGTH_LONG).show()

     RuntimeStatus.acquireWakeLock(applicationContext)
    }

    /**
     * 获得授权时会执行
     */
    override fun onBind(intent: Intent?): IBinder? {
        Toast.makeText(applicationContext, "Notice Listener Bind", Toast.LENGTH_LONG).show()

        return super.onBind(intent)
    }

    /**
     * 每次startService都会运行
     */
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Toast.makeText(applicationContext, "Notice Listener Start Command", Toast.LENGTH_LONG).show()
        Log.i("Notice"," Notice Listener Start Command")

        // 如果在极度极度低内存的压力下，该service还是会被kill掉，并且不一定会restart
        val boundnotice = RuntimeStatus.buildNotice(applicationContext, "AstroApp","请确保此通知一直存在" )
       startForeground(1, boundnotice)
        /*
        //绑定建立链接
        bindService(
            Intent(applicationContext, GuardService::class.java),
            connection, Context.BIND_IMPORTANT)
        */
        // 【结论】 手动返回 START_STICKY，亲测当service因内存不足被kill，当内存又有的时候，service又被重新创建，
        // 比较不错，但是不能保证任何情况下都被重建，比如进程被干掉了....
     //   return super.onStartCommand(intent, Service.START_STICKY, startId)
        return START_STICKY
    }

    override fun onDestroy() {
        Toast.makeText(applicationContext, "Notice Listener Destroyed", Toast.LENGTH_LONG).show()
     RuntimeStatus.releaseWakeLock()
       stopForeground(true)
     //   unbindService(connection)

        super.onDestroy()

        // 如果Service被杀死，干掉通知
        // NOTICE_ID
       // val mManager =
       //     getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
       // mManager.cancel(NOTICE_ID)
        // 重启自己
        val intent = Intent(applicationContext, NoticeListenerService::class.java)
        startService(intent)
    }


    override fun onListenerConnected() {
        super.onListenerConnected()
        Toast.makeText(applicationContext, "Notice Listener Connected", Toast.LENGTH_LONG).show()
    }

    override fun onListenerDisconnected() {
        super.onListenerDisconnected()
        Toast.makeText(applicationContext, "Notice Listener Disconnected", Toast.LENGTH_LONG).show()
    }

    override fun onNotificationPosted(sbn: StatusBarNotification?) {
     //   super.onNotificationPosted(sbn)
     //   Toast.makeText(applicationContext, "Notice Posted", Toast.LENGTH_LONG).show()
        Log.i("Notice"," ========== notice posted")

        sbn!!.notification ?: return
        val notice = NoticeInfo(sbn)
        Log.i("Notice",notice.toString())
    }

    override fun onNotificationRemoved(sbn: StatusBarNotification?) {
        super.onNotificationRemoved(sbn)
        Toast.makeText(applicationContext, "Notice Removed", Toast.LENGTH_LONG).show()
    }

    /*
    //创建一个ServiceConnection回调，通过IBinder进行交互
    // https://www.jianshu.com/p/9d5d988891d7
    private val connection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            //本句话借用：Android系统在同service的连接意外丢失时调用这个．
            // 比如当service崩溃了或被强杀了．当客户端解除绑定时，这个方法不会被调用．
            Log.e("ServiceStatus", "DisConnected: $name")

            //断开链接
            startService(Intent(applicationContext, GuardService::class.java))
            //重新绑定
            bindService(Intent(applicationContext, GuardService::class.java),
                this, Context.BIND_IMPORTANT)
        }

        override fun onServiceConnected(name: ComponentName?, iBinder: IBinder?) {
            Log.i("ServiceStatus", "Connected: $name")

            //下面是通过代理的方式将iBinder转成IMyAidlInterface
            val myAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder)
        }
    }
    */
}
